package com.sxx.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxx.commons.constant.ProductConstant;
import com.sxx.commons.dto.MemberPrice;
import com.sxx.commons.dto.SkuHasStockDTO;
import com.sxx.commons.dto.SkuReductionDTO;
import com.sxx.commons.dto.SpuBoundsDTO;
import com.sxx.commons.dto.es.SkuESModel;
import com.sxx.commons.utils.PageUtils;
import com.sxx.commons.utils.Query;
import com.sxx.commons.utils.R;
import com.sxx.mall.product.dao.SpuInfoDao;
import com.sxx.mall.product.entity.*;
import com.sxx.mall.product.feign.CouponFeignService;
import com.sxx.mall.product.feign.SearchFeignService;
import com.sxx.mall.product.feign.WareFeignService;
import com.sxx.mall.product.service.*;
import com.sxx.mall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    ProductAttrValueService productAttrValueService;
    @Autowired
    AttrService attrService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    BrandService brandService;
    @Autowired
    CategoryService categoryService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    //    保存发布商品信息
    @Override
    @Transactional
    public void saveSpuInfo(SpuInfoVO spuInfoVO) {
        //1.保存pms_spu_info信息，发布商品的库存商品的信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfoVO,spuInfoEntity);
        //创建时间和更新时间需要手动同步
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        spuInfoEntity.setPublishStatus(0);//设置发布状态为新建状态
        this.save(spuInfoEntity);
        Long spuId = spuInfoEntity.getId();
        //2.保存pms_spu_images信息，发布商品的库存商品图集信息
        spuInfoVO.getImages().forEach(img -> {
            SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
            spuImagesEntity.setImgUrl(img);
            spuImagesEntity.setSpuId(spuId);
            spuImagesEntity.setDefaultImg(0);//全部设为非默认，因为此时前端没传
            spuImagesService.save(spuImagesEntity);
        });
        //2.5保存pms_spu_info_desc信息，商品描述图片信息
        List<SpuInfoDescEntity> descEntityList = spuInfoVO.getDecript().stream().map(desc -> {
            SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
            spuInfoDescEntity.setDecript(desc);
            spuInfoDescEntity.setSpuId(spuId);
            return spuInfoDescEntity;
        }).collect(Collectors.toList());
        spuInfoDescService.saveBatch(descEntityList);

        //3.保存mall-sms下sms_spu_bounds信息，会员成长值信息
        Bounds bounds = spuInfoVO.getBounds();
        SpuBoundsDTO spuBoundsDTO = new SpuBoundsDTO();
        BeanUtils.copyProperties(bounds,spuBoundsDTO);
        spuBoundsDTO.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundsDTO);
        if (r.getCode() != 0){
            log.error("调用Coupon服务保存会员积分信息失败！");
        }


        //4.保存规格参数 pms_product_attr_value
        List<ProductAttrValueEntity> list = spuInfoVO.getBaseAttrs().stream().map(baseAttr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(baseAttr.getAttrId());
            productAttrValueEntity.setAttrValue(baseAttr.getAttrValues());
            productAttrValueEntity.setSpuId(spuId);//关联商品spu编号
            //设置商品属性的属性名称，attrservice根据id获取attr对象，再得到属性名，设置进去
            productAttrValueEntity.setAttrName(attrService.
                    getById(baseAttr.getAttrId()).getAttrName());
            productAttrValueEntity.setQuickShow(baseAttr.getShowDesc());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(list);

        //5.保存当前spu对应的所有sku信息
        List<Skus> skus = spuInfoVO.getSkus();
        if (null != skus && skus.size()>0){
            //5.1保存sku基本信息，
            skus.forEach(sku -> {
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                skuInfoEntity.setSpuId(spuId);
                skuInfoEntity.setSkuName(sku.getSkuName());
                skuInfoEntity.setSkuDesc(sku.getDescar().toString());
                skuInfoEntity.setCatalogId(spuInfoVO.getCatalogId());
                skuInfoEntity.setBrandId(spuInfoVO.getBrandId());
               // List<String> images = spuInfoVO.getImages();
                List<Images> images = sku.getImages();
                String defaultImg = "";
                for (Images img : images) {
                    if (img.getDefaultImg() == 1) {
                        //表示默认图片
                        defaultImg = img.getImgUrl();
                    }
                }
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoEntity.setSkuTitle(sku.getSkuTitle());
                skuInfoEntity.setSkuSubtitle(sku.getSkuSubTitle());
                skuInfoEntity.setPrice(sku.getPrice());
                skuInfoEntity.setSaleCount(0L);
                skuInfoService.save(skuInfoEntity);
                //5.2保存sku_images信息
                images.forEach(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    if (img.getDefaultImg() == 1){
                        skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                        skuImagesEntity.setImgUrl(img.getImgUrl());
                        skuImagesEntity.setDefaultImg(img.getDefaultImg());
                        skuImagesService.save(skuImagesEntity);
                    }

                });


                //5.3保存sku_sale_attr_value信息
                sku.getAttr().forEach(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    BeanUtils.copyProperties(attr,skuSaleAttrValueEntity);
                    skuSaleAttrValueService.save(skuSaleAttrValueEntity);
                });

                //5.4保存mall-sms下sms_sku_ladder折扣信息，sms_sku_full_reduction满减信息,sms_member_price会员价信息
                SkuReductionDTO skuReductionDTO = new SkuReductionDTO();
                BeanUtils.copyProperties(sku,skuReductionDTO);
//                List<MemberPrice> memberPrices = sku.getMemberPrice().stream().map(memberPrice -> {
//                    MemberPrice memberPrice1 = new MemberPrice();
//                    memberPrice1.setId(memberPrice.getId());
//                    memberPrice1.setName(memberPrice.getName());
//                    memberPrice1.setPrice(memberPrice.getPrice());
//                    return memberPrice1;
//                }).collect(Collectors.toList());
//                skuReductionDTO.setMemberPrice(memberPrices);

                skuReductionDTO.setSkuId(skuInfoEntity.getSkuId());
                R r1 = couponFeignService.saveFullReductionInfo(skuReductionDTO);
                if (r1.getCode() != 0){
                    log.error("调用Coupon服务保存满减、折扣和会员价信息失败！");
                }

            });


        }
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.and(w->{
                w.eq("id",key)
                        .or().like("spu_name",key)
                        .or().like("spu_description",key);
            });
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)){
            wrapper.eq("publish_status",status);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id",brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)){
            wrapper.eq("catalog_id",catelogId);//数据库字段写错了，写的catalog_id

        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );
        //修改显示的品牌、目录id为名字，从page中取出数据重新封装
        List<SpuInfoVO> list = page.getRecords().stream().map(spuInfo -> {
            SpuInfoVO spuInfoVO = new SpuInfoVO();
            BeanUtils.copyProperties(spuInfo, spuInfoVO);
            BrandEntity brandEntity = brandService.getById(spuInfo.getBrandId());
            CategoryEntity categoryEntity = categoryService.getById(spuInfo.getCatalogId());
            spuInfoVO.setBrandName(brandEntity.getName());
            spuInfoVO.setCatelogName(categoryEntity.getName());
            return spuInfoVO;
        }).collect(Collectors.toList());
        Page<SpuInfoVO> spuInfoVOPage = new Page<>();
        spuInfoVOPage.setRecords(list);
        spuInfoVOPage.setPages(page.getPages());
        spuInfoVOPage.setCurrent(page.getCurrent());
        return new PageUtils(spuInfoVOPage);
    }

/*
*   商品上架 商品相关数据存储到elasticsearch中
*   1，根据spuId查询 相关信息
*       封装到对象中
*   2.将封装的数据存储到elasticsearch中 调用mall-search的远程接口
*   3.更新spuId 对应的状态--》上架
* */
    @Override
    public void up(Long spuId) {
        // 1.根据spuId查询相关的信息 封装到SkuESModel对象中
        List<SkuInfoEntity> skus = skuInfoService.getSkuBySpuId(spuId);
        // 需要根据所有的skuId获取对应的库存信息---》远程调用
        List<Long> skuIds = skus.stream().map(sku -> {
            return sku.getSkuId();
        }).collect(Collectors.toList());
        Map<Long,Boolean> skuHasStockMap = getSkuHasStock(skuIds);
        //  封装到SkuESModel对象中
        List<SkuESModel> skuESModels = skus.stream().map(sku -> {
            SkuESModel skuESModel = new SkuESModel();
            BeanUtils.copyProperties(sku, skuESModel);
            skuESModel.setSubTitle(sku.getSkuSubtitle());
            skuESModel.setSkuPrice(sku.getPrice());
            skuESModel.setSkuImg(sku.getSkuDefaultImg());
            //是否还有库存
            if (skuHasStockMap != null && skuHasStockMap.size() != 0){
                Boolean hasStock = skuHasStockMap.get(sku.getSkuId());
                skuESModel.setHasStock(hasStock);
            }else {
                skuESModel.setHasStock(false);
            }
            skuESModel.setHotScore(0l);
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            skuESModel.setBrandName(brandEntity.getName());
            skuESModel.setBrandImg(brandEntity.getLogo());
            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
            skuESModel.setCatalogName(categoryEntity.getName());
            //attrs属性
            List<ProductAttrValueEntity> proAttrValues = productAttrValueService.getBySpuId(sku.getSpuId());
            List<SkuESModel.Attr> attrs = new ArrayList<>();
            proAttrValues.forEach(proAttrValue -> {
                //封装属性
                SkuESModel.Attr attr = new SkuESModel.Attr();
//                attr.setAttrId(proAttrValue.getAttrId());
//                attr.setAttrName(proAttrValue.getAttrName());
//                attr.setAttrValue(proAttrValue.getAttrValue());
                BeanUtils.copyProperties(proAttrValue,attr);
                //获取attr
                AttrEntity attrEntity = attrService.getById(proAttrValue.getAttrId());
                Integer searchType = attrEntity.getSearchType();
                //是否可搜索
                if (searchType == 1) {
                    //可搜索则保存
                    attrs.add(attr);
                }

            });
            //保存sku属性
            skuESModel.setAttrs(attrs);
            return skuESModel;
        }).collect(Collectors.toList());
        // 2.远程调用mall-search的服务，将SukESModel中的数据存储到ES中
        R statusUp = searchFeignService.productStatusUp(skuESModels);
        // 3.更新SPUID对应的状态
        //根据对应的状态更新商品的状态，上传到es成功
        if (statusUp.getCode() == 0){
            baseMapper.updateSpuStatusUp(spuId, ProductConstant.spuStatusEnum.SPU_UP.getCode());
        }
    }

    @Override
    public List<OrderItemSpuInfoVO> getOrderItemSpuInfoBySpuId(Long[] spuIds) {
        List<OrderItemSpuInfoVO> list = new ArrayList<>();
        for (Long spuId : spuIds) {
            OrderItemSpuInfoVO orderItemSpuInfoVO = new OrderItemSpuInfoVO();
            SpuInfoEntity spuInfoEntity = this.getById(spuId);
            orderItemSpuInfoVO.setId(spuId);
            orderItemSpuInfoVO.setSpuDescription(spuInfoEntity.getSpuDescription());
            orderItemSpuInfoVO.setSpuName(spuInfoEntity.getSpuName());
            orderItemSpuInfoVO.setBrandId(spuInfoEntity.getBrandId());
            orderItemSpuInfoVO.setCatalogId(spuInfoEntity.getCatalogId());
            //根据品牌编号查询品牌信息
            BrandEntity brandEntity = brandService.getById(spuInfoEntity.getBrandId());
            orderItemSpuInfoVO.setBrandName(brandEntity.getName());
            CategoryEntity categoryEntity = categoryService.getById(spuInfoEntity.getCatalogId());
            orderItemSpuInfoVO.setCatelogName(categoryEntity.getName());
            //获取spu图片
            List<SpuImagesEntity> spuImagesEntities = spuImagesService
                    .list(new QueryWrapper<SpuImagesEntity>().eq("spu_id", spuId));
            orderItemSpuInfoVO.setImg(spuImagesEntities.get(0).getImgUrl());
            list.add(orderItemSpuInfoVO);
        }
        return list;
    }


    /*

    */
/*
    * 更新spu状态为上架
    * *//*

    @Override
    public void updateSpuStatusUp(Long spuId, int code) {
        SpuInfoEntity spu = this.getById(new QueryWrapper<SpuInfoEntity>().eq("spu_id", spuId));
        spu.setPublishStatus(code);
        spu.setId(spuId);
        boolean update = this.update(new QueryWrapper<SpuInfoEntity>().setEntity(spu));
        System.out.println("--------update"+update);
    }
*/

    /**
     * 远程调用，根据skuIds获取全部sku库存
     * @param skuIds
     * @return 全部sku库存map
     */
    private Map<Long, Boolean> getSkuHasStock(List<Long> skuIds) {
        Map<Long,Boolean> map = new HashMap<>();
        if (skuIds == null && skuIds.size() == 0){
            return null;
        }
        try {
            List<SkuHasStockDTO> skuHasStockDTOS = wareFeignService.skuHasStock(skuIds);
            skuHasStockDTOS.forEach(skuHasStock->{
                skuHasStock.getSkuId();
                map.put(skuHasStock.getSkuId(), skuHasStock.getHasStock());
            });
            return map;
        }catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }
}